package com.guangaiboen.attendance.core.dispatcher.executor;

import com.guangaiboen.attendance.core.dispatcher.constants.RequestTypes;
import com.guangaiboen.attendance.core.dispatcher.context.DispatcherContext;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Post请求
 *
 * @param <T> 返回类型
 */
public abstract class PostHttpDispatcherExecutor<T> extends AbstractGenericHttpDispatcherExecutor<T> {

    private static final Logger log = LoggerFactory.getLogger(PostHttpDispatcherExecutor.class);

    @Override
    protected HttpRequestBase createHttpRequest(String url, DispatcherContext dispatcherContext) {
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = createEntity(url, dispatcherContext);
        try {
            dispatcherContext.setRequestBody(EntityUtils.toString(entity));
        } catch (IOException e) {
            log.warn(ExceptionUtils.getStackTrace(e));
        }
        httpPost.setEntity(entity);
        return httpPost;
    }

    protected abstract StringEntity createEntity(String url, DispatcherContext dispatcherContext);

    @Override
    protected String getRequestTypes() {
        return RequestTypes.POST.getRequestCode();
    }

}
